//tslint:disable
import { HttpService } from './../../shared/service/http.service';
import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { EventService } from 'src/app/shared/service/event.service';
import { ActionSheetController, AlertController } from "@ionic/angular";
@Component({
  selector: 'app-card-list-tag',
  templateUrl: './card-list-tag.component.html',
  styleUrls: ['./card-list-tag.component.scss'],
})
export class CardListTagComponent implements OnInit {
  @Input() tagData: any;
  emptyDataHint = '暂无数据';
  loadDataToBottom = '已经到底了~';
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  imgH: any;
  remainingTime: any
  remainingTimeNoShow: any
  timer;
  parentNode: any;
  childNodeArray: any;
  // 筛选及页面数据参数
  params: any = { content: {} };
  eventListenerName = 'appCardListTag';
  leftTop = 0;
  rightTop = 0;
  childArrayLength = 0;
  isNewData = false;
  showIonContent = false;
  isShowRefresher = false; // 2023.11.15 显示下拉刷新按钮
  refresherId = 'isShowRefresher';
  time: any;
  doRefreshListName = '';
  public refreshIds = new Set(); // 2024.11.19 refreshIds
  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private httpService: HttpService,
    private alertController: AlertController,
    private eventService: EventService,
  ) {

  }
  ngOnChanges() {
    if (this.tagData && this.tagData.pageTotal) {
      console.log("ngOnChanges!!!!" + this.tagData.pageTotal);
      this.checkLoadMore()
    }
  }
  checkLoadMore() {
    this.pageTotal = this.tagData.pageTotal;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    if (this.tagData.data.submit && this.tagData.data.submit.content) {
      this.params.content = this.tagData.data.submit.content;
    }
    if (this.tagData.hint !== undefined) {
      this.emptyDataHint = this.tagData.hint;
    }

    if (this.tagData.loadDataToBottomHint !== undefined) {
      this.loadDataToBottom = this.tagData.loadDataToBottomHint;
    }

    this.params.sessionId = localStorage.getItem("sessionId");
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
    if (this.tagData.maxShowNum && this.tagData.maxShowNum > 0 && this.tagData.data.data.length > this.tagData.maxShowNum) {
      // this.tagData.data.data =  this.tagData.data.data.slice(0,this.tagData.maxShowNum)
    }
  }
  ngOnInit() {
    let that = this;

    this.time = new Date().getTime();

    this.refresherId += new Date().getTime();
    // 2023.11.15 是否启用下拉刷新

    if (this.tagData.style !== this.tagData.name) {
      this.eventListenerName = this.tagData.name;
      // this.tagData.name = this.tagData.style;
    }

    const eventName = this.eventListenerName + "AskForList";
    if (this.eventService.eventEmit.listenerCount(eventName) > 0) {
      this.eventService.eventEmit.removeListener(eventName);
    }
    this.eventService.eventEmit.on(eventName, (obj) => {
      this.refreshListData(obj);
    });
    this.checkLoadMore();
    if (this.tagData.data.headDiv && this.tagData.data.headDiv.titleImg && this.tagData.data.headDiv.titleImg.endTime && this.tagData.data.headDiv.titleImg.endTime.length > 0) {
      this.tagData.data.headDiv.titleImg.endTime = this.tagData.data.headDiv.titleImg.endTime.replace(/-/g, "/");
      const timer = setInterval(() => {

        const stopTime: Date = new Date(this.tagData.data.headDiv.titleImg.endTime);
        const nowTime: Date = new Date();
        const jianGe = (stopTime.valueOf() - nowTime.valueOf()) / 1000;
        let day = Math.floor(jianGe / 60 / 60 / 24);
        let hour = Math.floor(jianGe / 60 / 60 % 24);
        let min = Math.floor(jianGe / 60 % 60);
        let sec = Math.floor(jianGe % 60);
        if (jianGe <= 0 || isNaN(jianGe)) {
          day = 0;
          hour = 0;
          min = 0;
          sec = 0;
        }
        let secStr = "00";
        let minStr = "00";
        let hourStr = "00";
        if (sec < 10) {
          secStr = '0' + sec;
        } else {
          secStr = sec + "";
        }
        if (min < 10) {
          minStr = '0' + min;
        } else {
          minStr = '' + min;
        }
        if (hour < 10) {
          hourStr = '0' + hour;
        } else {
          hourStr = hour + "";
        }


        this.remainingTime = day + '天 ' + hourStr + ':' + minStr + ':' + secStr;
        if (!this.remainingTimeNoShow) {
          this.remainingTimeNoShow = this.remainingTime;
        }
        if (day == 0 && hour == 0 && min == 0 && sec == 0) {
          //关闭定时器 
          clearInterval(this.timer);
        }
      }, 1000);
    }
  }

  moreClick(link) {
    if (link.type === 'tabClick') {
      if (link && link.params && link.params['tab_index']) {
        const tabIndex = parseInt(link.params['tab_index']);
        this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
        localStorage.setItem('subTab_index', link.params['subTab_index']);
      }
    } else {
      this.pageModalService.openPage(link);
    }
  }
  itemClick(link, e?) {
    if (e) {
      e.stopPropagation();
    }
    this.pageModalService.openPage(link);
    if (link && link.params.disableRefreshAfterLogin) {
      this.appGlobalService.disableRefreshAfterLogin = link.params.disableRefreshAfterLogin;
    }
  }


  itemSubmitClick(link, submit?, e?) {
    if (e) {
      e.stopPropagation();
    }
    if (link && submit) {
      const params = {
        content: submit.params,
        id: submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      // 请求获取新数据
      this.httpService.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success) {
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      },
        err => {
          // 请求数据失败
          this.appGlobalService.showToast(err.message, 2000, 'middle');
        });
      this.pageModalService.openPage(link);
    } else {
      this.pageModalService.openPage(link);
    }



  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (this.tagData.data.submit) {
      this.params.id = this.tagData.data.submit.id;
    }

    if (!param.showName) {
      if (this.tagData.data.submit && this.tagData.data.submit.content && this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    this.params.content = param;

    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        //2023年10月17日 pageTotal 更新
        if (res.data.submit && res.data.submit.content && res.data.submit.content.pageTotal) {
          this.pageTotal = res.data.submit.content.pageTotal;
        } else {
          this.pageTotal = this.tagData.pageTotal;
        }

        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
        setTimeout(() => {
          if (this.tagData.data.data && this.tagData.data.data[0] && this.tagData.data.data[0].isMacy !== undefined) {
            this.childArrayLength = 0;
            this.leftTop = 0;
            this.rightTop = 0;
            this.parentNode = document.querySelector('.list-bg');
            this.getNode(this.parentNode);
          }
        }, 10);
      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  loadMoreData(event) {
    try {
      if (!this.params) {
        this.params = { content: {} };
        this.params = this.tagData.data.submit.content;
      }
      this.pageNo = this.pageNo + 1;// // 参数
      this.params.content.pageNo = this.pageNo;
      this.params.id = this.tagData.data.submit.id;
      this.params.sessionId = localStorage.getItem("sessionId");
      this.askForData(event);
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }


  // type =0 标识刷新
  askForData(event, type?) {
    // 请求获取新数据
    this.httpService.post('application/submit', this.params, res => {
      // 请求数据成功
      if (res.success) {
        if (res.data.submit) {
          //2023年10月17日 pageTotal需要更新
          if (res.data.submit.content && res.data.submit.content.pageTotal) {
            this.pageTotal = res.data.submit.content.pageTotal;
          }
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        const resList = res.data.data;
        // 追加返回数据 ，刷新不追加
        if (resList && resList.length > 0 && type === undefined) {
          // 追加数据
          resList.map(v => {
            this.tagData.data.data.push(v);
          });

          setTimeout(() => {
            if (this.tagData.data.data && this.tagData.data.data[0] && this.tagData.data.data[0].isMacy !== undefined) {
              this.parentNode = document.querySelector('.list-bg');
              this.getNode(this.parentNode);
            }
          }, 10);
        } else {
          if (type === undefined) {
            if (event && event.target) {
              event.target.disabled = true;
            }
          } else {
            // 2024.09.03 如果是刷新则更新列表中的值
            this.tagData.data.data = res.data.data;
          }
        }
        this.isNewData = true;
      } else {
        if (type === undefined) {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, 'middle');         
        } else {
          this.pageNo = 1;
        }
      }
      if (event && event.target) {
        event.target.complete();
      }

    }, err => {
      if (type === undefined) { // 非刷新
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      } else {
        this.pageNo = 1;
      }
      if (event && event.target) {
        event.target.complete();
      }
    });
  }

  collectImg(subCollectDiv, e) {
    if (e) {
      e.stopPropagation();
    }
    if (subCollectDiv.button) {
      let tempParams = { content: "", id: "", sessionId: "" };
      tempParams.content = subCollectDiv.button.content;
      tempParams.id = subCollectDiv.button.id;
      tempParams.sessionId = localStorage.getItem("sessionId");
      try {
        this.httpService.post('application/submit', tempParams, res => {
          if (res.success) {

          }
        });
      } catch (error) {
      }
    } else if (subCollectDiv.loginLink) {
      this.pageModalService.openPage(subCollectDiv.loginLink.link);
      return;
    }
    subCollectDiv.selected = !subCollectDiv.selected;
    if (subCollectDiv.selected) {
      subCollectDiv.number = parseInt(subCollectDiv.number) + 1;
    } else {
      subCollectDiv.number = parseInt(subCollectDiv.number) - 1;
    }


    // if (document.getElementById('cardCollect' + id)) {
    //   if(document.getElementById('cardCollect' + id).getAttribute("src")==='assets/fw/solid.png'){

    //   }
    // }
  }

  async delete(button, event) {
    event.stopPropagation();
    const alert = await this.alertController.create({
      header: '',
      message: button.question,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let tempParams = { content: "", id: "", sessionId: "" };
            tempParams.content = button.deleteButton.content;
            tempParams.id = button.deleteButton.id;
            tempParams.sessionId = localStorage.getItem("sessionId");
            try {
              this.httpService.post('application/submit', tempParams, res => {
                if (res.success) {
                  if (localStorage.getItem('navCurrTabIndx')) {
                    const indx = 'fixedNavTab' + localStorage.getItem('navCurrTabIndx');
                    if (document.getElementById(indx)) {
                      document.getElementById(indx).click();
                    }
                  }
                }
              });


            } catch (error) {

            }
          }
        }
      ]
    });

    await alert.present();

  }

  ngAfterViewInit(): void {
    let that = this;
    // 2023.12.08 是否存在刷新控件
    if (this.tagData
      && this.tagData.data
      && this.tagData.data.data
      && this.tagData.data.data.length > 0) {
      // 2023.12.08 配置了某个属性才检查是否有下拉刷新事件
      if (this.tagData.data.data[0].isShowRefresher === 'true') {
        const debouncedHandler = that.appGlobalService.debounce((data: any) => {
          if (that.tagData.refreshId !== undefined) {
            that.eventService.eventEmit.emit(that.tagData.refreshId, '1');
          }
        }, 300);

        this.eventService.eventEmit.on('checkListIsShowRefresher', debouncedHandler);

        if (this.tagData.refreshId !== undefined) {
          that.tagData.refreshId += 'a';
          that.refreshIds.add(that.tagData.refreshId);
          console.log('init list name success!', that.tagData.refreshId);
          const debouncedHandler2 = that.appGlobalService.debounce((data: any) => {
            let tempRefresher = true;
            if (tempRefresher) {
              tempRefresher = false;
              let tempParamsContent = {};
              if (!that.params) {
                that.params = { content: {} };
                if (that.tagData.data.submit.content) {
                  that.params.content = that.tagData.data.submit.content;
                }
              } else {
                if (that.params && that.params.content) {
                  tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
                }
              }
              that.refreshListData(tempParamsContent);
              // that.refreshData(tempParamsContent);
              setTimeout(() => {
                tempRefresher = true; //防止2秒内重复请求
              }, 2000);
            }
          }, 300);
          that.eventService.eventEmit.on(that.tagData.refreshId, debouncedHandler2);


        }
      }

      if (this.tagData.data.data[0].showIonContent === 'true') {
        this.showIonContent = true;
      }
    }


    if (this.tagData.data.data && this.tagData.data.data[0] && this.tagData.data.data[0].isMacy !== undefined) {
      let timer = setTimeout(() => {
        this.parentNode = document.querySelector('.list-bg');
        this.getNode(this.parentNode);
        clearInterval(timer);
      }, 10);
    }
    if (this.tagData.data.data
      && this.tagData.data.data[0]
      && this.tagData.data.data[0].isShowRefresher !== undefined
      && this.tagData.data.data[0].isShowRefresher === 'true'
    ) {
      if (document.getElementById(this.refresherId)) {
        document.getElementById(this.refresherId).style.display = "block";
      }
    }

  }

  getNode(parentNode) {
    if (parentNode && parentNode !== undefined) {
      this.childNodeArray = document.getElementsByClassName("item-bg-card-list" + this.time);
      this.setImagePosition(this.childNodeArray);
    }
  }

  setImagePosition(childArray) {
    let divHeightArray = [];
    let heightNum1;
    let heightNum2;
    // 如果之前的数据数量不是偶数 比如 原来有9条 又新加9条， 第9条和第10条 无法进入高度差计算
    if (this.childArrayLength && this.childArrayLength % 2 !== 0) {
      this.childArrayLength = this.childArrayLength - 1;
    }

    for (let j = this.childArrayLength; j < childArray.length; j++) {
      divHeightArray[j] = childArray[j].offsetHeight; //取得div的高度
    }

    for (let i = this.childArrayLength ? Math.floor((this.childArrayLength) / 2) : 0; i < Math.ceil((childArray.length) / 2); i++) {

      heightNum1 = divHeightArray[i * 2];
      heightNum2 = divHeightArray[((i + 1) * 2) - 1];

      if (heightNum1 !== undefined && heightNum2 !== undefined) {
        if (heightNum1 === heightNum2) {
          if (this.rightTop > 0 && childArray[((i + 1) * 2) - 1]) {
            this.childNodeArray[((i + 1) * 2) - 1].style.top = '-' + this.rightTop + 'px';
            if (this.childNodeArray[((i + 2) * 2) - 1]) {
              this.childNodeArray[((i + 2) * 2) - 1].style.top = '-' + this.rightTop + 'px';
            }
          }
          if (this.leftTop > 0 && childArray[i * 2]) {
            this.childNodeArray[i * 2].style.top = '-' + this.leftTop + 'px';
            if (this.childNodeArray[(i + 1) * 2]) {
              this.childNodeArray[(i + 1) * 2].style.top = '-' + this.leftTop + 'px';
            }
          }

        } else if (heightNum1 > heightNum2) {
          // 如果下拉刷新出新数据 并且第一次出现高度差
          if (this.isNewData === true) {
            if (this.rightTop > 0 && childArray[((i + 1) * 2) - 1]) {
              this.childNodeArray[((i + 1) * 2) - 1].style.top = '-' + this.rightTop + 'px';
              if (this.childNodeArray[((i + 2) * 2) - 1]) {
                this.childNodeArray[((i + 2) * 2) - 1].style.top = '-' + this.rightTop + 'px';
              }
            }
            if (this.leftTop > 0 && childArray[i * 2]) {
              this.childNodeArray[i * 2].style.top = '-' + this.leftTop + 'px';
              if (this.childNodeArray[(i + 1) * 2]) {
                this.childNodeArray[(i + 1) * 2].style.top = '-' + this.leftTop + 'px';
              }
            }
          }

          this.rightTop += heightNum1 - heightNum2;
          // 如果有这个div

          if (this.leftTop > 0 && this.childNodeArray[(i + 1) * 2]) {
            this.childNodeArray[(i + 1) * 2].style.top = '-' + this.leftTop + 'px';
          }

          if (this.childNodeArray[((i + 2) * 2) - 1]) {
            this.childNodeArray[((i + 2) * 2) - 1].style.top = '-' + this.rightTop + 'px';
          } else {
            this.isNewData = false;
          }
        } else if (heightNum1 < heightNum2) {
          // 如果下拉刷新出新数据 并且第一次出现高度差
          if (this.isNewData === true) {
            if (this.rightTop > 0 && childArray[((i + 1) * 2) - 1]) {
              this.childNodeArray[((i + 1) * 2) - 1].style.top = '-' + this.rightTop + 'px';
              if (this.childNodeArray[((i + 2) * 2) - 1]) {
                this.childNodeArray[((i + 2) * 2) - 1].style.top = '-' + this.rightTop + 'px';
              }
            }
            if (this.leftTop > 0 && childArray[i * 2]) {
              this.childNodeArray[i * 2].style.top = '-' + this.leftTop + 'px';
              if (this.childNodeArray[(i + 1) * 2]) {
                this.childNodeArray[(i + 1) * 2].style.top = '-' + this.leftTop + 'px';
              }
            }
          }

          this.leftTop += heightNum2 - heightNum1;
          // 如果有这个div

          if (this.rightTop > 0 && this.childNodeArray[((i + 2) * 2) - 1]) {
            this.childNodeArray[((i + 2) * 2) - 1].style.top = '-' + this.rightTop + 'px';
          }

          if (this.childNodeArray[(i + 1) * 2]) {
            this.childNodeArray[(i + 1) * 2].style.top = '-' + this.leftTop + 'px';
          } else {
            this.isNewData = false;
          }
        }
      }
    }

    this.childArrayLength = childArray.length;

  }


  ngOnDestroy(): void {
    if (this.tagData && this.refreshIds) {
      this.refreshIds.forEach(element => {
        this.eventService.removeCustomListListenersByName(element);
      });
    }
    this.eventService.removeCustomListListenersByName(this.tagData.name + 'AskForList');
    this.leftTop = 0;
    this.rightTop = 0;
    this.childArrayLength = 0;
  }
  getInterger(value) {
    return parseInt(value, 10);
  }

  // 2023.12.05 特定字符串加标志位来访问改方法
  doRefresh(event) {
    if (!this.params) {
      this.params = { content: {} };
      this.params = this.tagData.data.submit.content;
    }
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    this.params.id = this.tagData.data.submit.id;
    this.params.sessionId = localStorage.getItem("sessionId");
    const type = 0;// type =0 标识刷新
    this.askForData(event, type);

  }
}
